<?php include 'functions.php'; echo $html_doctype; ?>
<html>
<head>
<title> Scratch Resources | XML Test</title>
<?php
	echo $html_meta;
	echo $html_css;
	echo $html_scripts;
?>
</head>

<body>
<!-- HEADER -->
<div id="maincontainer">
	<?php include 'header.php'; ?>
	
	<div class="box_fullwidth">
	<h1>XML test</h1>
	
	<?php
	$xml = simplexml_load_file('http://scratch.mit.edu/feeds/getRecentGalleryProjects/70848');
	//var_dump($xml);
	//reads Scratch gallery RSS feed.
	resdap_connect();
	foreach ($xml->channel->item as $item) {
		$title = $item->title;
		$link  = $item->link;
		$img   = $item->imagelink;
		$descr = $item->description;
		$descr = substr($descr, (strpos($descr, '/>')+2)); // ' /&gt;'
		
		$a = substr($link, 32); //remove the http://scratch.mit.edu/ and keep user/123456
		$creator = substr($a, 0, strpos($a,'/'));
		$projectid = substr($a, strpos($a,'/')+1);
		
		//Check if the project is already in the database
		$q = "SELECT * FROM res_tutprojects WHERE projectid=$projectid";
		resdap_connect();
		$result = mysql_query($q);
		if(mysql_num_rows($result)==0) {
			//The project is not in the database, store it!
			dev_out("New project found: '$title' by $creator");
			$qValues = "'" . mysql_real_escape_string($title) . "', '" . mysql_real_escape_string($creator) . "', '" . mysql_real_escape_string($descr) . "', '" . mysql_real_escape_string($projectid) ."');";
			$q =  "INSERT INTO res_tutprojects ( title, creator, description, projectid) VALUES(" . $qValues;
			mysql_query($q) or die(mysql_error());
			dev_out("Saved '$title'.");
		} else {
			dev_out("Project '$title' already in database.");
		}		
	}
	resdap_disconnect();
	?>
	
	</div>
	
	<?php include('footer.php'); ?>
</div>
</body>

</html>
